import { getRequest } from "../reuqest/request";

// 获取区编码
const getAreaCode = (v1, v2) => {
  return new Promise((resolve, reject) => {
    const ak = "YXsq4yk8DXaM6l77v2WtbaLGXVOXx96r";
    const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${ak}&output=json&location=${v1},${v2}`;
    wx.request({
      url: url,
      success: function (res) {
        if (res.data && res.data.result && res.data.result.addressComponent) {
          let address = JSON.parse(
            JSON.stringify(res.data.result.addressComponent)
          );
          resolve(address.adcode);
          return;
        }
        uni.showToast({
          title: "获取区编码失败",
          icon: "none",
        });
        reject("");
      },
      fail: function (res) {
        uni.showToast({
          title: "获取区编码失败",
          icon: "none",
        });
        reject("");
      },
    });
  });
};

// 根据城市渲染地图中心
const getCityCenter = cityName => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `https://api.map.baidu.com/geocoding/v3/?address=${cityName}&output=json&ak=YXsq4yk8DXaM6l77v2WtbaLGXVOXx96r`,
      method: "GET",
      success: res => {
        if (res.statusCode === 200) {
          const result = res.data.result;
          if (result) {
            const location = result.location;
            console.log(`${cityName}的中心点坐标：`, location);
            resolve({ latitude: location.lat, longitude: location.lng });
          } else {
            console.error("未找到城市中心信息");
            reject({ latitude: 0, longitude: 0 });
          }
        } else {
          console.error("请求失败，状态码：", res.statusCode);
          reject({ latitude: 0, longitude: 0 });
        }
      },
      fail: err => {
        console.error("请求出错：", err);
        reject({ latitude: 0, longitude: 0 });
      },
    });
  });
};

const getUrl = url => {
  return new Promise((resolve, reject) => {
    getRequest(`/wx-operation/api/v1/c/file/get/${url}`).then(res => {
      resolve(res.url);
    });
  });
};

const getParams = (queryParam, carInfo) => {
  let data = {
    // 车辆归属网点id
    vehicleBelongStoreUuid: queryParam.storeUuid,
    // 车型uuid
    modelUuid: queryParam.modelUuid,
    startTime: queryParam.startTime,
    endTime: queryParam.endTime,
    // 是否上门取车 0-否; 1-是;
    visitPickFlag: carInfo.commonInfo.visitPickFlag ? 1 : 0,
    // 是否上门还车 0-否; 1-是;
    visitBackFlag: carInfo.commonInfo.visitBackFlag ? 1 : 0,
    // 是否异地还车 0-否; 1-是;
    remoteBackFlag: carInfo.commonInfo.remoteBackFlag ? 1 : 0,
    vehicleBackLatitude: carInfo.backInfo.latitude, // 还车纬度
    vehicleBackLongitude: carInfo.backInfo.longitude, // 还车精度
    vehiclePickLatitude: carInfo.pickInfo.latitude, // 取车纬度
    vehiclePickLongitude: carInfo.pickInfo.longitude, // 取车精度
    vehiclePickStoreUuid: carInfo.pickInfo.storeUuid, // 车辆取车网点id
    vehicleBackStoreUuid: carInfo.backInfo.storeUuid, // 车辆还车网点id
    // 取还车区域code
    vehiclePickAreaCode: carInfo.pickInfo.vehiclePickAreaCode,
    vehicleBackAreaCode: carInfo.backInfo.vehicleBackAreaCode,
    // 取还车详细地址
    vehiclePickAddressDetail: carInfo.pickInfo.addressDetail,
    vehicleBackAddressDetail: carInfo.backInfo.addressDetail,
  };
  // 非异地送取车
  if (!carInfo.commonInfo.remoteBackFlag) {
    data.vehicleBackLatitude = data.vehiclePickLatitude;
    data.vehicleBackLongitude = data.vehiclePickLongitude;
    data.vehicleBackStoreUuid = data.vehiclePickStoreUuid;
    data.vehicleBackAreaCode = data.vehiclePickAreaCode;
    data.vehicleBackAddressDetail = data.vehiclePickAddressDetail;
    if (carInfo.commonInfo.visitPickBackFlag) {
      data.visitPickFlag = 1;
      data.visitBackFlag = 1;
    }
  }
  console.log(data, "data", !carInfo.commonInfo.remoteBackFlag);
  return data;
};
// formatTimestamp(Date.now(), "YYYY-MM-DD") // 2025-05-07
// formatTimestamp(Date.now(), "MM/DD HH:mm") // 05/07 18:22
// formatTimestamp(Date.now(), "YYYY年MM月DD日 HH点mm分") // 2025年05月07日 18点22分
const formatTimestamp = (timestamp, format = "YYYY-MM-DD") => {
  const date = new Date(timestamp);
  const pad = n => n.toString().padStart(2, "0");

  const map = {
    YYYY: date.getFullYear(),
    MM: pad(date.getMonth() + 1),
    DD: pad(date.getDate()),
    HH: pad(date.getHours()),
    mm: pad(date.getMinutes()),
    ss: pad(date.getSeconds()),
  };

  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, key => map[key]);
};

const weekMap = new Map([
  [0, "周一"],
  [1, "周二"],
  [2, "周三"],
  [3, "周四"],
  [4, "周五"],
  [5, "周六"],
  [6, "周天"],
]);

/**
 * 获取车型配置
 * @param {*} list 车型list
 * @returns string 车型配置
 */
const getCarConfig = list => {
  if (list && list.length > 0) {
    let temp = list;
    if (list.length > 3) {
      temp = list.slice(0, 3);
    }
    return temp.map(item => item.vehicleModelExtValue).join(" / ");
  }
  return "";
};

const formatStr = (str, weekend = "0") => {
  let arr = [];
  if (!str) return "-";
  str.split("").map((item, index) => {
    if (item == weekend) {
      arr.push(weekMap.get(index));
    }
  });
  return arr.join("、");
};

export default {
  getAreaCode,
  getUrl,
  getCityCenter,
  getParams,
  getCarConfig,
  formatTimestamp,
  formatStr,
};
